package com.lbx.controller;

import com.alibaba.fastjson.JSON;
import com.lbx.entity.SysUser;
import com.lbx.mapper.SysUserMapper;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Base64;
import java.util.HashMap;

/**
 * @author lbx create by 2021/6/8 15:48
 * @apiNote ViewController
 */
@Controller
@CrossOrigin
public class ViewController {
    @Resource
    private SysUserMapper userMapper;
    
    /**
     * @param url   其他应用登录成功需要跳转的页面
     * @param model 。。
     * @return java.lang.String
     * @apiNote toLoginPage 登录页面 所有应用统一的登录页面
     */
    @GetMapping("/loginPage/{url}")
    public String toLoginPage(@PathVariable String url, Model model) {
        byte[] decoded = Base64.getDecoder().decode(url);
        String decodeStr = new String(decoded);
        System.err.println(decodeStr);
        model.addAttribute("url", decodeStr);
        return "loginPage";
    }
    /**
     * @param username 注册用户名
     * @param password 注册密码
     * @return java.lang.String
     * @apiNote userRegister
     */
    @PostMapping("/userRegister")
    @ResponseBody
    public String userRegister(String username, String password) {
        int i = 0;
        HashMap<String, Object> map = new HashMap<>();
        SysUser one = userMapper.getOneByUsername(username);
        if (one!=null){
            map.put("code",500);
            map.put("msg","用户已经存在");
            return JSON.toJSONString(map);
        }
        try {
            i = userMapper.insetUser(username, password);
        } catch (Exception e) {
            map.put("code",500);
            map.put("msg",e.getMessage());
            return JSON.toJSONString(map);
        }
        if (i == 1) {
            map.put("code",200);
            map.put("msg","注册成功，赶快登录吧");
        } else {
            map.put("code",-1);
            map.put("msg","注册失败，未知异常");
        }
        return JSON.toJSONString(map);
    }
    
    @GetMapping("/")
    @Secured("ROLE_SYSTEM")
    public String admin(){
        return "admin/admin";
    }
    @GetMapping("/loginPage")
    public String LoginPage() {
        return "loginPage";
    }
}

